package com.didispace.chapter11;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
public class HelloController {
    private volatile boolean stop = false;

    static ExecutorService executorService;

    static {
        executorService = Executors.newFixedThreadPool(2);
    }

    @RequestMapping("/cpu")
    public String cpu() {
        long start = System.currentTimeMillis();
        double res = 0;
        for (double i = 0; i < 10000000 ; i++) {
            res = Math.sqrt(i);
        }
        System.out.println("耗时："+(System.currentTimeMillis()-start));
        return "Hello World";
    }

    @RequestMapping("/morethread")
    public String morethread() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                while (!stop){
                    Thread.yield();
                }
                System.out.println("结束");
            }).start();
        }

        System.out.println("耗时："+(System.currentTimeMillis()-start));
        return "Hello morethread";
    }

    @RequestMapping("/morethreadStop")
    public String morethreadStop() {
        stop = true;
        return "stop morethreadStop";
    }


    @RequestMapping("/morethreadPool")
    public String morethreadPool() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 20; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    while (!stop) {
                        Thread.yield();
                    }
                    System.out.println("结束");
                }
            });
        }
        System.out.println("耗时："+(System.currentTimeMillis()-start));
        return "Hello morethreadPool";
    }


    @RequestMapping("/morethreadPoolLeak")
    public String morethreadPoolLeak() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 20; i++) {
            ExecutorService es = Executors.newFixedThreadPool(2);
            es.execute(new Runnable() {
                @Override
                public void run() {
                    while (!stop) {
                        Thread.yield();
                    }
                    System.out.println("结束");
                }
            });
        }
        System.out.println("耗时："+(System.currentTimeMillis()-start));
        return "Hello morethreadPoolLeak";
    }



}